package com.youlian.utils.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author simon
 *
 */
public class HttpClientUtils {
	private String userAgent = null;
	private String charset = "UTF-8";

	/**
	 * 得到HttpClient方法
	 *
	 * @return
	 */

	public static HttpClient getHttpClient(int timeOut) {
		HttpParams httpParams = new BasicHttpParams();

		// 判断手机客户端连接的cmwap网络，设置代�?
		if (isWap()) {
			// MyLog.error(HttpClientUtils.class,
			// "***************************cmwap***********************");
			HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
			// 10.0.0.200
			httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		}
		httpParams.setParameter("Accpet-Encoding", "gzip");
		HttpConnectionParams.setConnectionTimeout(httpParams, timeOut * 1000);
		HttpConnectionParams.setSoTimeout(httpParams, timeOut * 1000);
		HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

		HttpClientParams.setRedirecting(httpParams, true);

		// String userAgent =
		// "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
//		if (StringUtils.isNull(Constants.userAgent)) {
//			Constants.userAgent = ApkManager.getApkInfo();
//		}
//		HttpProtocolParams.setUserAgent(httpParams, Config.userAgent);
		return new DefaultHttpClient(httpParams);

	}

	/**
	 * 执行doGet方法
	 *
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String doGet(String url) throws Exception {
		HttpGet httpRequest = new HttpGet(url);
		String strResult = "";

		HttpResponse httpResponse = getHttpClient(30).execute(httpRequest);
		strResult = EntityUtils.toString(httpResponse.getEntity(), charset);
		strResult = filterHtml(strResult);

			System.out.println(" reqURL : " + url);
			System.out.println(" response : " + strResult);
			System.out.println("---------------------------------------------");

		return strResult;
	}

	public String doGet(String url, String charset) throws Exception {
		/* 建立HTTPGet对象 */
		HttpGet httpRequest = new HttpGet(url);
		String strResult = "";

		/* 发�?请求并等待响�?*/
		HttpResponse httpResponse = getHttpClient(30).execute(httpRequest);
		strResult = EntityUtils.toString(httpResponse.getEntity(), charset);
		strResult = filterHtml(strResult);

			System.out.println(" reqURL : " + url);
			System.out.println(" response : " + strResult);
			System.out.println("---------------------------------------------");

		return strResult;
	}

	/**
	 *
	 * @param url
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public String doPost(String url, String charset, String data)
			throws Exception {
		/* 建立HTTPGet对象 */
		HttpPost httpRequest = new HttpPost(url);
		String strResult = "";

		// 设置HTTP POST请求参数必须用NameValuePair对象

		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("keywords", data));

		// 设置HTTP POST请求参数
		httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		/* 发�?请求并等待响�?*/
		HttpResponse httpResponse = getHttpClient(30).execute(httpRequest);
		strResult = EntityUtils.toString(httpResponse.getEntity(), charset);
		strResult = filterHtml(strResult);

			System.out.println(" reqURL : " + url);
			System.out.println(" response : " + strResult);
			System.out.println("---------------------------------------------");

		return strResult;
	}

	/**
	 *
	 * @param strUrl
	 * @param outData
	 * @param codeStr
	 * @return
	 */
	public String duPost(String strUrl, StringBuffer outData, String codeStr) {
		String defaultCodeStr = null;
		HttpURLConnection httpConn = null;
		String xmlStr = null;
		try {
			httpConn = (HttpURLConnection) new URL(strUrl).openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setReadTimeout(15000);
			httpConn.setConnectTimeout(15000);
			httpConn.setInstanceFollowRedirects(false);
			// send out data using POST method
			httpConn.setRequestMethod("POST");
			httpConn.connect();
			if (codeStr != null && !"".equals(codeStr)) {
				defaultCodeStr = codeStr;
			}
			DataOutputStream dout = new DataOutputStream(
					httpConn.getOutputStream());
			if (outData != null)
				dout.write(outData.toString().getBytes(defaultCodeStr));
			dout.flush();
			dout.close();
			// receive the response
			xmlStr = null;
			int rspCode = httpConn.getResponseCode();
			System.out.print("rspCode :" + rspCode + "\r\n");
			int i = 0;
			// process HTTP 200-OK
			if (rspCode == HttpsURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						httpConn.getInputStream(), defaultCodeStr));
				String strLine;
				StringBuffer rspBuf = new StringBuffer();
				while ((strLine = br.readLine()) != null) {
					rspBuf.append(strLine + "\r\n");
				}
				xmlStr = rspBuf.toString();
				br.close();
				httpConn.getInputStream().close();
				httpConn.disconnect();
				return xmlStr;
			}
			return xmlStr;
		} catch (Exception e) {
			xmlStr = null;
			e.printStackTrace();
			return xmlStr;
		}
	}

	/**
	 * 执行doGet方法，失败返回null
	 *
	 * @param url
	 * @return InputStream
	 */
	public InputStream doGet4stream(String url) throws ClientProtocolException,
			IOException {
		HttpGet httpRequest = new HttpGet(url);
		HttpResponse httpResponse = getHttpClient(60).execute(httpRequest);

		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return httpResponse.getEntity().getContent();
		}
		return null;
	}

	/**
	 * 过滤特殊字符
	 *
	 * @param result
	 * @return
	 */
	private String filterHtml(String result) {
		if (null != result) {
			result = result.replace("&#039;", "'");
			result = result.replace("&amp;", "&");
			result = result.replace("&nbsp;", " ");
		}
		return result;
	}

	// 判断网络类型
	public static boolean isWap() {
		String proxyHost = android.net.Proxy.getDefaultHost();
		if (proxyHost != null) {
			return true;
		} else {
			return false;
		}
	}
}
